package ballpool;

import game.Constants;
import game.GameMap;
import game.TwistyBasicGameState;

import java.util.ArrayList;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.StateBasedGame;

import vision.Vision;

/**
 * Ballpool Game.
 * @author Twisty
 *
 */
public class BallpoolGame extends TwistyBasicGameState {
	// All of the balls within this game.
	private ArrayList<Ball> balls = new ArrayList<Ball>();

	// Initialize step number.
	private long step = 0;
	
	// Amount of balls in game. Change if your fps is too low!
	private int BALLAMOUNT = 500;
	
	/**
	 * Class constructor.
	 * @param vision	The Vision object for recognizing differences in camera.
	 */
	public BallpoolGame(Vision vision) {
		super(vision);
	}

	@Override
	public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException {
		//Add ballpool balls
		for(int i = 0; i < BALLAMOUNT; i++){
			int rX = ((int) (Math.random()*Constants.screenWidth));
			int rY = ((int) (Math.random()*Constants.screenHeight));
			
			//Make sure they stay in the map width and height
			rX = rX -32;
			rY = rY -32;
			if(rX < 0) rX = 0;
			if(rY < 0) rY = 0;
			
			//Add ball
			balls.add(new Ball(rX, rY));
		}
		map = new GameMap(Constants.screenWidth, Constants.screenHeight);
	}

	@Override
	public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
		super.update(container, game, delta);
		
		for(Ball b: balls){
			if(b.getX() > Constants.screenWidth || b.getY() > Constants.screenHeight){
				// Remove ball if out of bounds.
				balls.remove(b);
			}
			b.step(map, step);
			b.move(map);
		}
		step++;
	}

	@Override
	public void render(GameContainer container, StateBasedGame game, Graphics g)
			throws SlickException {
		for(Ball b: balls){
			g.setColor(b.getColor());
			g.fillOval(b.getX(), b.getY(), b.getWidth(), b.getHeight());
		}
		//Uncomment if you want to see the collision points on the map
		
		for(int y = 0; y < this.map.getHeight(); y++){
			for(int x = 0; x < this.map.getWidth(); x++){
				if(this.map.hasPointAtLocation(x,y)){
					g.drawRect(x, y, 1, 1);
				}
			}
		}
	}

	@Override
	public int getID() {
		// TODO Auto-generated method stub
		return Constants.ballpoolGame;
	}
}
